#!/bin/bash

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2009-2016 Stephan Raue (stephan@openelec.tv)
# Copyright (C) 2018-present Team LibreELEC (https://libreelec.tv)

if [ -z "$1" ]; then
  echo "Usage: $0 <branch-name>"
  exit 0
fi

ROOT=$(cd $(dirname $0)/../.. && pwd)

KODI_BRANCH="$1"
KODI_DIR="kodi-${KODI_BRANCH}.git"

git_clone() {
  # git_clone https://repo.url branch ./target_dir [githash]
  echo "[mkpkg] Checking out $1 ..."
  if [ ! -d "$3" ]; then
    git clone "$1" "$3"
    # Try to switch to specified branch if it exist, if not then use default branch
    if [ -n "$2" ]; then
      cd "$3"
      git checkout $2 >/dev/null 2>/dev/null
      cd ..
    fi
  else
    if [ -d "$3" ] ; then
      cd "$3"
      git checkout $2 >/dev/null 2>/dev/null
      git pull
      cd ..
    fi
  fi

  if [ ! -z "$4" ] ; then
    cd "$3"
    git fetch >/dev/null 2>/dev/null
    git branch -D $4 >/dev/null 2>/dev/null
    git checkout $4 >/dev/null 2>/dev/null
    git checkout -b ref-$4 >/dev/null 2>/dev/null
    cd ..
  fi
}

resolve_hash() {
  if [ -d "$1" ] ; then
    cd "$1"
    git rev-parse $2 2>/dev/null
  fi
}

# Get url in git:// notation for a package.mk, assuming it is a github.com url
# Return 1 if not a github domain
geturl() {
  local addon="$1"
  local domain owner repo PKG_URL

  PKG_URL="$(get_pkg_var ${addon} PKG_URL)"

  domain="$(echo "${PKG_URL}" | cut -d/ -f3)"
  [ "${domain}" = "github.com" ] || return 1

  owner="$(echo "${PKG_URL}" | cut -d/ -f4)"
  repo="$(echo "${PKG_URL}" | cut -d/ -f5)"

  echo "git://${domain}/${owner}/${repo}.git"
  return 0
}

# For the specified addon, verify that the package url
# matches the url retrieved from Kodi
validate_pkg_url() {
  local addon="$1" url1="$2"
  local domain owner repo url2

  domain="$(echo "${url1}" | cut -d/ -f3)"
  owner="$(echo "${url1}" | cut -d/ -f4)"
  repo="$(echo "${url1}" | cut -d/ -f5)"

  url1="git://${domain}/${owner}/${repo}.git"
  url2="$(geturl "${addon}")"

  [ "${url1}" = "${url2}" ] && return 0 || return 1
}

get_pkg_var() {
  local pkg_name="$1" pkg_var="$2"
  cd ${ROOT}
  PROJECT=Generic ARCH=x86_64 source config/options ${pkg_name} &>/dev/null
  echo "${!pkg_var}"
}

update_pkg() {
  local pkg_path="$1" pkg_name="$2" pkg_version="$3"
  local old_version pkg_url new_sha256

  old_version=$(get_pkg_var "${pkg_name}" PKG_VERSION)

  if [ "${old_version}" != "${pkg_version}" ]; then
    [ -n "$pkg_version}" ] && sed -e "s|PKG_VERSION=.*|PKG_VERSION=\"${pkg_version}\"|g" -i ${pkg_path}

    pkg_url=$(get_pkg_var "${pkg_name}" PKG_URL)

    new_sha256="$(wget -q ${pkg_url} -O- | sha256sum | awk '{print $1}')" || exit 1
    sed -e "s|PKG_SHA256=.*|PKG_SHA256=\"${new_sha256}\"|g" -i ${pkg_path}
  fi
}

if [ ! -d ${KODI_DIR} ] ; then
  git_clone https://github.com/xbmc/xbmc ${KODI_BRANCH} ${KODI_DIR}
fi

# p8-platform
REPO=$(cat $KODI_DIR/cmake/addons/depends/common/p8-platform/p8-platform.txt | awk '{print $2}')
GIT_HASH=$(cat $KODI_DIR/cmake/addons/depends/common/p8-platform/p8-platform.txt | awk '{print $3}')
PKG_NAME="p8-platform"

git_clone $REPO master $PKG_NAME.git $GIT_HASH
if [ -f ${ROOT}/packages/mediacenter/p8-platform/package.mk ] ; then
  # update package.mk
  RESOLVED_HASH=$(resolve_hash $PKG_NAME.git $GIT_HASH)
  echo "Resolving hash for ${PKG_NAME}: ${GIT_HASH} => ${RESOLVED_HASH}"
  sed -i "s|PKG_VERSION=.*|PKG_VERSION=\"$RESOLVED_HASH\"|g" ${ROOT}/packages/mediacenter/p8-platform/package.mk
fi
rm -rf $PKG_NAME.git

# kodi-platform
REPO=$(cat $KODI_DIR/cmake/addons/depends/common/kodi-platform/kodi-platform.txt | awk '{print $2}')
GIT_HASH=$(cat $KODI_DIR/cmake/addons/depends/common/kodi-platform/kodi-platform.txt | awk '{print $3}')
PKG_NAME="kodi-platform"

git_clone $REPO master $PKG_NAME.git $GIT_HASH
if [ -f ${ROOT}/packages/mediacenter/kodi-platform/package.mk ] ; then
  # update package.mk
  RESOLVED_HASH=$(resolve_hash $PKG_NAME.git $GIT_HASH)
  update_pkg ${ROOT}/packages/mediacenter/kodi-platform/package.mk ${PKG_NAME} ${RESOLVED_HASH}
fi
rm -rf $PKG_NAME.git

# addons
for addontxt in $KODI_DIR/cmake/addons/bootstrap/repositories/*-addons.txt ; do
  ADDONS=$(cat $addontxt | awk '{print $1}')
  ADDONREPO=$(cat $addontxt | awk '{print $2}')
  GIT_HASH=$(cat $addontxt | awk '{print $3}')
  git_clone $ADDONREPO ${KODI_BRANCH} $ADDONS.git $GIT_HASH
  for addon in $ADDONS.git/*.*/ ; do
    ADDON=$(basename $addon)

    [[ ${ADDON} =~ ^game.* ]] && continue # ignore game.* addons - handled by update_retroplayer-addons

    REPO=$(cat $addon/$ADDON.txt | awk '{print $2}')
    GIT_HASH=$(cat $addon/$ADDON.txt | awk '{print $3}')
    PKG_NAME="$ADDON"

    # Verify the Kodi repo matches our package repo
    # If different, ignore the addon and process it later as an "unofficial" addon
    validate_pkg_url "$ADDON" "$REPO" || continue

    PROCESSED="${PROCESSED}${PKG_NAME}\n"

    if ! grep -q all $addon/platforms.txt && ! grep -q linux $addon/platforms.txt && ! grep -q ! $addon/platforms.txt; then
      continue
    fi

    if [ -f ${ROOT}/packages/mediacenter/kodi-binary-addons/$ADDON/package.mk ] ; then
      git_clone $REPO ${KODI_BRANCH} $PKG_NAME.git $GIT_HASH

      # update package.mk
      RESOLVED_HASH=$(resolve_hash $PKG_NAME.git $GIT_HASH)
      echo "Resolving hash for ${PKG_NAME}: ${GIT_HASH} => ${RESOLVED_HASH}"
      update_pkg ${ROOT}/packages/mediacenter/kodi-binary-addons/$ADDON/package.mk ${PKG_NAME} ${RESOLVED_HASH}

      rm -rf $PKG_NAME.git
    else
      echo "[mkpkg] Skipped $ADDON"
      SKIPPED_ADDONS="$SKIPPED_ADDONS $ADDON"
    fi
  done

  echo
  echo "The following addons were skipped, please add packages for these addons:"
  echo "[${SKIPPED_ADDONS}]"
  echo
done

# finally, any other unofficial addons
for ADDON in $(ls -1 ${ROOT}/packages/mediacenter/kodi-binary-addons); do
  [[ ${ADDON} =~ ^game.* ]] && continue # ignore game.* addons - handled by update_retroplayer-addons

  # ignore already processed addons
  echo -e "${PROCESSED}" | grep -qE "^${ADDON}$" && continue

  # Obtain git url - ignore if not a suitable repo
  REPO="$(geturl "${ADDON}")" || continue

  git_clone $REPO ${KODI_BRANCH} $ADDON.git HEAD

  # update package.mk for stale github.com packages
  RESOLVED_HASH=$(resolve_hash ${ADDON}.git HEAD) || continue
  echo "Resolving hash for ${ADDON}: HEAD => ${RESOLVED_HASH}"
  update_pkg ${ROOT}/packages/mediacenter/kodi-binary-addons/$ADDON/package.mk ${ADDON} ${RESOLVED_HASH}

  rm -rf $ADDON.git
done
